//管理长连接对象
namespace chatroom{
    typedef websocketpp::server<websocketpp::config::asio> server_t;
    class Connection{
        public:
            using Ptr = std::shared_ptr<Connection>;
            struct Client{
                Client(const std::string& user_id,const std::string& session_id)
                :uid(user_id),sessid(session_id){}
                std::string uid,    //用户id
                std::string sessid //登录会话ID
            };
            bool insert(const server_t::connection_ptr& con,const std::string& uid,const std::string& ssid){
                std::unique<std::mutex> mutex(_mutex);
                if(_uid_connection.find(uid)!=_uid_connection.end())
                {
                    Logger_ERROR("已经存在该{}的长连接了",uid);
                    return false;
                }
                _uid_connection.insert(make_pair(uid,con));
                _client_connection.insert(make_pair(con,Client(uid,ssid)));
                return true;
            }

            server_t::connection_ptr find(const std::string& uid){
                std::unique<std::mutex> mutex(_mutex);
                auto it = _uid_connection.find(uid);
                if(uid==_uid_connection.end())
                {
                    Logger_ERROR("不存在该用户的长连接{}",(size_t)_uid_connection.get());
                    return erver_t::connection_ptr();
                }
                return it->second;
            }
            bool client(const server_t::connection_ptr& con,std::string& uid,std::string& ssid)
            {
                std::unique<std::mutex> mutex(_mutex);
                auto it = _client_connection.find(con);
                if(it==_client_connection.end())
                {
                    Logger_ERROR("找不到对方客户端的长连接");
                    return false;
                }
                uid = it->second.uid;
                ssid = it->second.sessid;
                return true;
            }
            bool remove(const server_t::connection_ptr& con)
            {
                std::unique<std::mutex> mutex(_mutex);
                auto it = _client_connection.find(con);
                if(it==_client_connection.end())
                {
                    Logger_ERROR("没有该长连接");
                    return false;
                }
                _client_connection.erase(it);
                _uid_connection.erase(it->second.uid);
                return true;
            }
        private:
            std::mutex _mutex;
            std::unordered_map<uid,server_t::connection_ptr> _uid_connection;
            std::unordered_map<server_t::connection_ptr,Client> _client_connection;
    };
}